package com.xtaller.lazy.api.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xtaller.lazy.base.TApi;
import com.xtaller.lazy.lib.R;
import com.xtaller.lazy.lib.annotation.Permission;
import com.xtaller.lazy.lib.convert.J;
import com.xtaller.lazy.lib.convert.M;
import com.xtaller.lazy.lib.convert.V;
import com.xtaller.lazy.model.system.Authorities;
import com.xtaller.lazy.parameter.DocAuthorities;
import com.xtaller.lazy.service.system.AuthoritiesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-04-09
 * @Description: 权限管理
 */
@Api(tags = "系统模块api")
@RestController
@RequestMapping("/v1/system")
public class AuthoritiesApi extends TApi {
    @Autowired private AuthoritiesService authoritiesService;

    private Map<String, String> baseVerify() {
        var verify = M.create("name", "名称不能为空");
        return verify;
    }

    @GetMapping("/authorities/{moduleId}")
    @ApiOperation("读取数据")
    @Permission(authorities = "system-authorities-table")
    public Object table(@ApiParam("页码") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                        @ApiParam("页长") @RequestParam(value = "limit", required = false, defaultValue = "1000") int limit,
                        @ApiParam("模块id") @PathVariable Long moduleId){
        var p = new Page<Authorities>(page, limit);
        var qw = new QueryWrapper<Authorities>();
        qw.lambda()
                .eq(Authorities::getModuleId, moduleId)
                .orderByDesc(Authorities::getOrderNumber);
        var data = authoritiesService.page(p, qw);
        var auths = data.getRecords();

        // 处理子项数据
        var parents = getAuthByParentId(auths, 0L, 0);
        var obj = J.o2l(parents);

        obj.stream().forEach(o -> {
            var sub = getAuthByParentId(auths, o.getLong("id"), 0);
            var subs = J.o2l(sub);
            if(sub.size() > 0){
                subs.stream().forEach(s -> {
                    var permission = getAuthByParentId(auths, s.getLong("id"), 1);
                    // type 排正序
                    permission.sort(Comparator.comparing(Authorities::getType));
                    s.put("id", s.getString("id"));
                    s.put("moduleId", s.getString("moduleId"));
                    s.put("parentId", s.getString("parentId"));
                    s.put("count", permission.size());
                    s.put("permission", permission);
                });
            }
            o.put("id", o.getString("id"));
            o.put("moduleId", o.getString("moduleId"));
            o.put("parentId", o.getString("parentId"));
            o.put("count", subs.size());
            o.put("sub", subs);
        });

        var result = p2t(data);
        result.put("data", obj);
        return result;
    }



    @PostMapping("/authorities")
    @ApiOperation("创建数据")
    @Permission(authorities = "system-authorities-create")
    public Object create(@ApiParam("数据对象") @RequestBody DocAuthorities object){
        var check = V.checkEmpty(baseVerify(), object);
        if (check.getBoolean(CHECK)) {
            return R.error(check.getString(MESSAGE));
        }
        var model = J.o2m(object, Authorities.class);
        model.setCreateId(userId.get());

        model = authoritiesService.model(model);
        if(model == null) {
            return R.error("数据创建失败");
        }
        return R.ok("数据创建成功", model);
    }

    @PutMapping("/authorities/{id}")
    @ApiOperation("修改数据")
    @Permission(authorities = "system-authorities-update")
    public Object update(@ApiParam("数据id") @PathVariable Long id, @ApiParam("数据对象") @RequestBody DocAuthorities object){
        var model = authoritiesService.getById(id);

        if(model == null) {
            return R.error("数据id异常");
        }

        var check = V.checkEmpty(baseVerify(), object);
        if (check.getBoolean(CHECK)) {
            return R.error(check.getString("message"));
        }

        model = J.o2m(object, Authorities.class);
        model.setId(id);
        model.setUpdateId(userId.get());

        model = authoritiesService.model(model);
        if(model == null) {
            return R.error("数据修改失败");
        }
        return R.ok("数据修改成功", model);
    }

    @DeleteMapping("/authorities/{id}")
    @ApiOperation("删除数据")
    @Permission(authorities = "system-authorities-delete")
    public Object delete(@ApiParam("数据id") @PathVariable Long id){
        var model = authoritiesService.getById(id);
        if(model == null) {
            return R.error("数据id异常");
        }
        if(authoritiesService.removeById(id)) {
            return R.ok("数据删除成功", J.create("id", id));
        }
        return R.error("数据删除失败");
    }
}
